#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 读写字节数据
问题: 你想读写二进制文件，比如图片，声音文件等等。
提示 : 
"""


def recipe1():
    filename1 = '04_rw_binary_1.bin'
    with open(filename1, 'wb') as f:
        f.write(b'Hello World')

    with open(filename1, 'rb') as f:
        print(f.read())

    # 文件中读取或写入文本数据
    filename2 = '04_rw_binary_2.bin'
    with open(filename2, 'wb') as f:
        text = 'Hello World！张三'
        f.write(text.encode('utf-8'))

    with open(filename2, 'rb') as f:
        data = f.read(30)
        print(f"{data.decode('utf-8') = }")


def recipe2():
    '''二进制I/O还有一个鲜为人知的特性就是数组和C结构体类型能直接被写入'''
    import array
    nums = array.array('i', [1, 2, 3, 4])
    filename3 = '04_rw_binary_3.bin'
    with open(filename3, 'wb') as f:
        f.write(nums)

    with open(filename3, 'rb') as f:
        print(f.read())

    # 这种技术的时候需要格外小心，因为它通常具有平台相关性
    a = array.array('i', [0, 0, 0, 0, 0, 0, 0, 0])
    with open(filename3, 'rb') as f:
        f.readinto(a)
    print(f"{a = }")

class Info:
    def __init__(self, name) -> None:
        self.name = name

    def __repr__(self) -> str:
        return 'Info({!r})'.format(self.name)

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()

if __name__ == '__main__':
    main()
